/*
The code examples copyrighted by Nokia Corporation that are included to
this material are licensed to you under following MIT-style License:

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <QDebug>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>

#include <MAction>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MList>
#include <MContainer>
#include <MContentItem>

#include <gconf/gconf-client.h>

#include "SimpleApplet.hpp"



const char* DGConfDir = "/apps/simple-applet";
const char* DGConfVariableKey = "/apps/simple-applet/sample-value";



Q_EXPORT_PLUGIN2(simple-applet, SimpleApplet)



SimpleSettingsSingleton* SimpleSettingsSingleton::inst = 0;



SimpleSettingsSingleton::SimpleSettingsSingleton() :
		selectedValueIndex(0)
{
	Q_ASSERT(!inst);
	
	inst = this;
	
	this->possibleValues.append("Value 1");
	this->possibleValues.append("Value 2");
	this->possibleValues.append("Value 3");
	this->possibleValues.append("Value 4");
	this->possibleValues.append("Value 5");
	this->possibleValues.append("Value 6");
	this->possibleValues.append("Value 7");
	
	//Load setting from GConf
	this->Load();
}



SimpleSettingsSingleton::~SimpleSettingsSingleton(){
	Q_ASSERT(inst);
	
	inst = 0;
}



void SimpleSettingsSingleton::SetValue(QString value){
	int index = this->possibleValues.indexOf(value);
	if(index < 0 || this->possibleValues.size() <= index){
		this->selectedValueIndex = 0;
	}else{
		this->selectedValueIndex = unsigned(index);
	}
	emit selectionChanged();
}



void SimpleSettingsSingleton::Save(){
	g_type_init();
	
	//Get the default GConf client
	GConfClient *client = gconf_client_get_default();
	
	//Save the setting to persistent storage (GConf)
	{
		QString value = SimpleSettingsSingleton::Instance().GetCurrentValue();
	
		if(value.size() > 0){
			gconf_client_set_string(client, DGConfVariableKey, value.toUtf8().constData(), NULL);
		}else{
			gconf_client_unset(client, DGConfVariableKey, NULL);
		}
	}
	
	/* 
	* This ensures we cleanly detach from the GConf server (assuming
	* we hold the last reference).
	*/
	g_object_unref(G_OBJECT(client));
}



void SimpleSettingsSingleton::Load(){
	g_type_init();

	//Get the default GConf client
	GConfClient *client = gconf_client_get_default();
	
	//Add GConf directory
	gconf_client_add_dir(
			client,
			DGConfDir,
			GCONF_CLIENT_PRELOAD_NONE,
			NULL
		);
	
	//Read in the current setting value from persistent storage (GConf)
	char* str = gconf_client_get_string(client, DGConfVariableKey, NULL);
	if(str){
		QString s = QString::fromUtf8(str);
		g_free(str);
		
		this->SetValue(s);
	}
	
	/* 
	 * This ensures we cleanly detach from the GConf server (assuming
	 * we hold the last reference).
	 */
	g_object_unref(G_OBJECT(client));
}



void SimpleApplet::init(){}



DcpWidget* SimpleApplet::constructWidget(int /* widgetId */){
	return new SimpleAppletWidget();
}



QString SimpleApplet::title()const{
    return QString("SimpleApplet");
}



QVector<MAction*> SimpleApplet::viewMenuItems(){
	//return empty vector, no menu items provided by this applet
    QVector<MAction*> vector;
    return vector;
}



DcpBrief* SimpleApplet::constructBrief(int){
    return new SimpleBrief();
}



/*
Cell creator class to be used with MList.
*/
class SimpleCellCreator: public MAbstractCellCreator<MContentItem>{
public:
	//override
	virtual MWidget * createCell(const QModelIndex &index, MWidgetRecycler &recycler) const{
		MContentItem * cell = qobject_cast<MContentItem*>(recycler.take("MContentItem"));
		if(!cell){
			cell = new MContentItem(MContentItem::SingleTextLabel);
		}
		this->updateCell(index, cell);
		
		return cell;
	}
	
	//override
	virtual void updateCell(const QModelIndex& index, MWidget *cell) const{
		MContentItem * contentItem = qobject_cast<MContentItem*>(cell);
		QString txt = index.data(Qt::UserRole + 1).toString();
		contentItem->setTitle(txt);
	}
};



SimpleAppletWidget::SimpleAppletWidget(QGraphicsWidget *parent) :
		DcpWidget(parent)
{
	this->setReferer(-1); //no referer
	
	QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(this);

	QStringList values = SimpleSettingsSingleton::Instance().GetListOfPossibleValues();
	
	QStandardItemModel* model = new QStandardItemModel();
	QItemSelectionModel* selectionModel = new QItemSelectionModel(model);
	foreach(QString v, values){
		QStandardItem* item = new QStandardItem(v);
		item->setData(v);
		model->appendRow(item);
		if(SimpleSettingsSingleton::Instance().GetCurrentValue() == v){
			selectionModel->select(item->index(), QItemSelectionModel::ClearAndSelect);
		}
	}

	//SelectContainer
	this->selectContainer = new MList();
	this->selectContainer->setCellCreator(new SimpleCellCreator());
	
	this->selectContainer->setItemModel(model);
	this->selectContainer->setSelectionMode(MList::SingleSelection);
	this->selectContainer->setSelectionModel(selectionModel);
	this->selectContainer->setColumns(2);
	QObject::connect(
			this->selectContainer,
			SIGNAL(itemClicked(const QModelIndex &)),
			this,
			SLOT(OnItemClicked(const QModelIndex &))
		);

	this->container = new MContainer(this);
	this->container->setCentralWidget(this->selectContainer);
	layout->addItem(this->container);
	
	this->container->setTitle("Select value");
}



void SimpleAppletWidget::OnItemClicked(const QModelIndex &index){
	this->selectContainer->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
}



bool SimpleAppletWidget::back(){
	
	if(this->selectContainer->selectionModel()->selectedIndexes().size() == 0)
		return true;//true means "close the applet"
	
	SimpleSettingsSingleton::Instance().SetValue(
			this->selectContainer->selectionModel()->selectedIndexes()[0].data().toString()
		);
		
	//Save settings to GConf
	SimpleSettingsSingleton::Instance().Save();
	
	return true;//true means "close the applet"
}
